import Vue from 'vue'
import msgVue from './msg.vue'
import './msg.less'
import { install } from 'vuex';
const msgConstructor = Vue.extend(msgVue)

let instance
let instances = []
let index = 1

/**
 * msg
 * @param {Object} options 
 * @param {Number} options.duration   持续时间(s)
 * @param {Number} options.type       类型(success,warning, info, error)
 * @param {String} options.message    内容 
 * @param {Function} options.onClose  关闭回调函数
 */
let Msg = (options = {}) => {
    if (typeof options === 'string') {
        options = {
            message: options
        }
    }
    options.duration = options.duration || 3000
    options.type = options.type || 'success'
    options.message = options.message || ''
    options.btns = options.btns || []
    options.onClose = options.onClose || null
    options.success = options.success || null

    instance = new msgConstructor()
    instance.$mount()
    document.body.appendChild(instance.$el)
    instance.visible = true

    instance.index = index++
    instance.type = options.type
    instance.message = options.message
    instance.onClose = options.onClose
    instance.duration = options.duration
    instances.push(instance)
    return instance
}

['success', 'warning', 'info', 'error'].forEach(type => {
    Msg[type] = options => {
        if (typeof options === 'string') {
            options = {
                message: options
            }
        }
        options.type = type
        return Msg(options)
    }
})
Msg.close = (index) => {
    for (let i = 0, len = instances.length; i < len; i++) {
        if (index == instances[i].index) {
            instances[i].close()
            instances.splice(i, 1)
            break
        }
    }
}
Msg.install = (Vue) => {
    Vue.msg = Vue.prototype.$msg = Msg
}

export default Msg
export { Msg }